package com.gdgk.shop.admin.task;

import com.gdgk.shop.bean.model.ScoreImportDetail;
import com.gdgk.shop.bean.model.ScoreImportRecord;
import com.gdgk.shop.dao.ScoreImportDetailMapper;
import com.gdgk.shop.dao.ScoreImportRecordMapper;
import com.gdgk.shop.service.ScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
@EnableScheduling // 开启定时任务
public class ChangeScoreTask {

    @Autowired
    private ScoreImportRecordMapper scoreImportRecordMapper;

    @Autowired
    private ScoreImportDetailMapper scoreImportDetailMapper;

    @Autowired
    private ScoreService scoreService;

    @Scheduled(cron = "0 0/1 * * * ?")  //间隔1分钟，只能串行 不能修改为多线程
    public void PointsDistributeSchedule() throws Exception {
        System.out.println("当前时间：" + LocalDateTime.now().toLocalTime());
        // 1.取 *_score_import_record 表status为0的记录，程序是串行的
        ScoreImportRecord scoreImportRecord = scoreImportRecordMapper.getOneByStatus();
        log.info(scoreImportRecord == null?"待处理导入记录为空":"待处理导入记录：" + scoreImportRecord.getId());
        if (scoreImportRecord == null) {
            return;
            // 处理 null 的情况，例如：
            //throw new IllegalArgumentException("scoreImportRecord cannot be null");
        }
        // 2.根据id查询明细表中各条明细，待处理
        List<ScoreImportDetail> detailList  = scoreImportDetailMapper.selectByRecordId(scoreImportRecord.getId());
        // 3.调用积分发放函数，循环遍历（1）根据手机号 修改用户表 用户积分 （2）根据手机号 修改明细表 状态从0变1， 最后（3）根据record_id 修改记录表 状态从0变1
        scoreService.pointsDistribution(detailList, scoreImportRecord.getId());

    }


//    @Scheduled(cron = "0/30 * * * * *")  //间隔30秒
    public void TestSchedule() throws Exception {
        boolean boo = scoreService.bindingScoreByMobile("12300001111", "123abc");
        System.out.println(boo);

    }

//    @Scheduled(cron = "0/30 * * * * *")  //间隔30秒
    public void Test2Schedule() throws Exception {
        // boolean boo = scoreService.subtractScoreByPay("12300001111", 2);
        // System.out.println(boo);

    }

}
